<template>
  <div>
    <Drawer title="节点配置" :mask-closable="false" :before-close="handleClose" :closable="false" v-model="drawerVisible"
      width="80%" class="drawerStyle">
      <Button type="primary" @click="handleAddRow" :disabled="buttonDisable">新增</Button>

      <Tabs v-model="currentTab" @tab-click="handleTabClick">
        <TabPane v-for="tab in tabs" :key="tab.name" :label="tab.label" :name="tab.name">
          <Table :columns="columns[currentTab]" border :data="listData[currentTab]">
            <template slot-scope="{ row }" slot="action">
              <span class="operationBtn" @click="handleEditRow(row)"><i class="iconfont zy-common-bianji"></i>编辑</span>
              <span class="operationBtn" @click="handleDeleteRow(row)"><i
                  class="iconfont zy-common-shanchu"></i>删除</span>
            </template>
          </Table>
        </TabPane>
      </Tabs>
      <div class="demo-drawer-footer">
        <Button style="margin-right: 8px" @click="handleClose">取消</Button>
        <Button type="primary" @click="handleSure">确定</Button>
      </div>
    </Drawer>
    <commonModal ref="commonModal"></commonModal>
    <RouterModal :visible="modalVisible" :form="form" :title="title" :handleAddSubmit="handleAddSubmit"
      :closeModal="closeModal" :materialData="materialData" :currentTab="currentTab" :storageList="storageList"
      :materialAllApiList="materialAllApiList" :equipmentList="equipmentList" :quality="quality"
      :materialList='materialList' :handleAdd="handleAdd" :handleRemove='handleRemove' />
  </div>
</template>

<script>
import { Button, Popconfirm, Tabs, TabPane } from 'element-ui';

import RouterModal from './components/routerModal';
import commonModal from '@/components/modalTypes/commonModal.vue';
import { editResourceApi, addResourceApi, deleteResourceApi, productResourceApi, basedataMaterialAllApi } from '@/api/dataBasic/process';
import { basedataStorageAllApi, basedataEquipmentAllApi, storageMaterialAllApi, storageMaterialsAllApi } from '@/api/dataBasic/process';
export default {
  name: "DrawerProcess",
  components: {
    commonModal,
    Button,
    RouterModal,
    Popconfirm,
    Tabs,
    TabPane
  },
  props: {
    drawerVisible: Boolean,
    drawerClose: Function,
    currentItem: Object,
    processList: Array,
    processTotal: Number,
    productProcess: Function,
    materialData: Array,

  },
  data() {
    return {
      queryPage: { current: 1, pageSize: 10 },
      modalVisible: false,
      form: {},
      title: '',
      modalVisibleProcess: false,
      columns: {
        equipment: [
          {
            title: '设备名称',
            key: 'equipmentId',
            align: 'center',
            render: (h, params) => {
              const name = this.equipmentList.find(i => i.id === params.row.equipmentId);
              return h('div', name.equipmentName);
            }
          },

          {
            title: "操作",
            slot: "action",
            fixed: "right",
            width: 180,
            align: "center"
          }
        ],
        storage: [
          {
            title: '储位名称',
            key: 'storageId',
            align: 'center',
            render: (h, params) => {
              const name = this.storageList.find(i => i.id === params.row.storageId);
              return h('div', name.storageName);
            }
          },

          {
            title: '投入物料',
            key: 'putMaterialId',
            align: 'center',
            render: (h, params) => {
              const names = params.row.keys.map(item => {
                const name = this.materialList.find(i => i.id === item.putMaterialId);
                return name.materialName;
              })

              return h('div', names.join(','));
            }
          },
          {
            title: '产出物料',
            key: 'outMaterialId',
            align: 'center',
            render: (h, params) => {
              const name = this.materialList.find(i => i.id === params.row.outMaterialId);
              return h('div', name.materialName);
            }
          }, {
            title: '产出物料与产品比',
            key: 'numPutCompare',
            align: 'center',

          },
          {
            title: "操作",
            slot: "action",
            fixed: "right",
            width: 180,
            align: "center"
          }
        ],
        tool: [
          {
            title: '夹具编码',
            key: 'toolingId',
            align: 'center',
            render: (h, params) => {
              const name = this.materialAllApiList.find(i => i.id === params.row.toolingId);
              return h('div', name.toolingCode);
            }
          },

          {
            title: "操作",
            slot: "action",
            fixed: "right",
            width: 180,
            align: "center"
          }
        ],
        quality: [
          {
            title: '质检名称',
            key: 'qualityName',
            align: 'center',

          },
          {
            title: '质检类型',
            key: 'qualityType',
            align: 'center',

          },

          {
            title: "操作",
            slot: "action",
            fixed: "right",
            width: 180,
            align: "center"
          }
        ]

      }


      ,
      currentTab: 'storage', // 当前选中的标签名
      tabs: [
        { name: 'storage', label: '储位' },
        { name: 'equipment', label: '设备' },
        { name: 'tool', label: '夹具' },
        { name: 'quality', label: '质检' }
      ],

      storageList: [],
      materialAllApiList: [],
      equipmentList: [],
      listResource: [],
      materialList: [],
      listData: {
        storage: [],
        equipment: [],
        tool: [],
        quality: []
      },
      buttonDisable: false,
      quality: ["首件检", "换班检", "周期检"],
      index: 0,
    };
  },
  mounted() {

  },
  watch: {
    async drawerVisible(newValue, oldValue) {
      if (newValue) {
        await this.featAll()
        await this.productResourceApi()


      } else {
        this.listData = {
          storage: [],
          equipment: [],
          tool: [],
          quality: []
        },
          this.listResource = {}
        this.currentTab = 'storage'
      }
    }
  },
  methods: {
    handleRemove(index) {
      this.form.keys.splice(index, 1)
    },
    handleAdd() {
      this.index++;
      if (this.form.keys) {
        this.form.keys.push({
          // value: '',
          putMaterialId: '',
          ratio: '',
          index: this.index,
          status: 1
        });
      } else {
        this.form = {
          ...this.form,
          keys: [{
            // value: '',
            index: this.index,
            status: 1
          }]
        }
      }

    },
    handleTabClick() {

      if (['storage', 'tool'].includes(this.currentTab) && this.listData[this.currentTab].length === 1) {
        this.buttonDisable = true
      } else {
        this.buttonDisable = false
      }
      console.log(this.buttonDisable, 'ssss')
    },

    handleSure() {
      //
      const dataJson = {
        ...this.listData,
        storage: this.listData.storage.map(i => {
          return {
            numPutCompare: i.numPutCompare,
            outMaterialId: i.outMaterialId,
            storageId: i.storageId,
            keys: i.keys,
            outMaterial: [{
              MaterialId: i.outMaterialId,
              numPutCompare: i.numPutCompare
            }],
            IntMaterial: i.keys.map(item => {
              return {
                MaterialId: item.putMaterialId,
                numPutCompare: item.numPutCompare,
              }
            })
          }

        })


      }
      console.log(this.listData, 'this.listData')
      const configJson = JSON.stringify(dataJson)
      const params = { procedureId: this.currentItem.id, configJson }
      //代表有替换
      console.log(params, 'params')
      if (this.listResource.id) {
        editResourceApi({ ...params, id: this.listResource.id }).then(res => {
          if (res.code === 200) {
            this.$Message.success('保存成功!');
            this.productResourceApi()
          }
        })
        return
      }
      addResourceApi(params).then(res => {
        if (res.code === 200) {
          this.$Message.success('保存成功!');
          this.productResourceApi()
        }
      })

    },
    featAll() {
      basedataStorageAllApi({}).then(res => {
        if (res.code === 200) {
          this.storageList = res.data;
        }
      })

      basedataEquipmentAllApi({}).then(res => {
        if (res.code === 200) {
          this.equipmentList = res.data;
        }
      })
      basedataMaterialAllApi().then(res => {
        if (res.code === 200) {
          this.materialList = res.data;
        }
      })
      storageMaterialAllApi({}).then(res => {
        if (res.code === 200) {
          this.materialAllApiList = res.data;
        }

      })

    },

    productResourceApi() {
      productResourceApi({
        procedureId: this.currentItem.id
      }).then(res => {
        if (res.code === 200) {

          if (res.data.records.length > 0) {
            const jsonResource = res.data.records[0]
            this.listResource = jsonResource
            const JsonData = JSON.parse(jsonResource.configJson)
            const regroup = {
              ...JsonData,
              storage: JsonData.storage.map(item => {
                return {
                  ...item,
                  outMaterialId: item.outMaterial[0].MaterialId,
                  numPutCompare: item.outMaterial[0].numPutCompare
                }
              }),


            }
            this.listData = regroup
            console.log(this.listData, 'this.listData', regroup)
            this.handleTabClick()
          }
        }
      })
    },
    closeModal() {
      this.modalVisible = false;
    },
    changePageNum(val) {
      this.queryPage.current = val;
      this.productProcess({
        materialBomId: this.currentItem.id,
        ...this.queryPage,
      });
    },
    changePageSize(val) {
      this.queryPage.pageSize = val;
      this.productProcess({
        materialBomId: this.currentItem.id,
        ...this.queryPage,
      });
    },
    replaceItemById(items, newItem) {
      const newData = items.map(i => {
        if (i.index_id === newItem.index_id) {
          return newItem;
        }
        return newItem
      })
      return newData
    },
    handleAddSubmit() {

      const ids = Math.floor(Math.random() * 100)
      if (this.currentTab === 'equipment') {
        if (this.form.edit) {
          const dataNew = this.replaceItemById(this.listData.equipment, this.form)
          this.listData = {
            ...this.listData,
            equipment: dataNew
          }

        } else {
          this.listData = {
            ...this.listData,
            equipment: [...this.listData.equipment, { equipmentId: this.form.equipmentId, index_id: ids }]
          }
        }

      }
      if (this.currentTab === 'storage') {//只有一个
        this.listData = {
          ...this.listData,
          storage: [this.form]
        }
      }
      if (this.currentTab === 'tool') {
        this.listData = {
          ...this.listData,
          tool: [{ toolingId: this.form.toolingId }]
        }
      }
      if (this.currentTab === 'quality') {
        console.log(this.currentTab, this.form, 'sssssss')
        if (this.form.edit) {
          const dataNew = this.replaceItemById(this.listData.quality, this.form)
          this.listData = {
            ...this.listData,
            quality: dataNew
          }

        } else {
          if (this.listData.quality) {
            this.listData = {
              ...this.listData,
              quality: [...this.listData.quality, { ...this.form, index_id: ids }]
            }
          } else {
            this.listData = {
              ...this.listData,
              quality: [{ ...this.form, index_id: ids }]
            }
          }

        }

      }
      this.modalVisible = false;
      this.handleTabClick()
    },
    handleClose(done) {
      this.drawerClose();
    },
    handleAddRow() {
      this.title = '新增';
      if (['quality', 'storage'].includes(this.currentTab)) {
        this.form = { keys: [{}] };
      }
      this.modalVisible = true;
    },
    handleEditRow(row, flag) {

      this.modalVisible = true;
      this.form = { ...row, edit: true };
      this.title = '编辑';
    },
    handleDeleteRow(row) {
      this.$refs.commonModal.showModal({
        title: '删除提醒',
        type: 'warn',
        desc: '是否确认删除？',
        submit: () => {
          if (['equipment', 'quality'].includes(this.currentTab)) {
            const dataNew = this.listData[this.currentTab].filter(i => i.index_id !== row.index_id)
            this.listData = {
              ...this.listData,
              [this.currentTab]: dataNew
            }
          } else {
            this.listData = {
              ...this.listData,
              [this.currentTab]: []
            }
          }
          this.handleTabClick()
        },
      });
    },

  }
};
</script>

<style lang="scss" scoped>
.operationBtn {
  cursor: pointer;
  margin-right: 10px;
}

.tableContent {
  padding: 25px;
}

.drawerZIndex {
  ::v-deep.ivu-drawer-wrap {
    z-index: 12000 !important;
  }

  ::v-deep.ivu-drawer-mask {
    z-index: 11000 !important;
  }
}

.demo-drawer-footer {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}
</style>